import argparse
import copy
import json
import os

import requests

from utils.configs import GiteeConfig

from urllib3.exceptions import InsecureRequestWarning

from utils.header_pool import get_headers

# 禁用警告
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

headers = {
    "Authorization": f"token {GiteeConfig.TOKEN}"
}


def create_check(owner: str, repo: str, pull_id: int, name: str, output_path: str = None,
                 head_sha: str = None, pull_request_id: str = None):
    if not head_sha or not pull_request_id:
        pull_url = GiteeConfig.URL_ROOT + owner + "/" + repo + "/pulls/" + str(pull_id)
        print(f"create_check get pull info...pull id : {pull_id}, ci name: {name}")
        response = requests.get(pull_url, verify=False, headers=get_headers(pull_url))
        if response.status_code != 200:
            print(f"pull get error: {response.status_code}")
            return
        response_json = json.loads(response.text)
        pull_request_id = response_json["id"]
        head_sha = response_json["head"]["sha"]

    output_json = None
    if output_path:
        file_json = get_file_data(output_path)
        if file_json is not None:
            output_json = file_json["output"]

    body = {
        "name": name,
        "head_sha": head_sha,
        "pull_request_id": pull_request_id,
        "output": output_json
    }
    # print(f"create check body: {body}")
    print(f"add check {name}...")
    create_url = GiteeConfig.URL_ROOT + owner + "/" + repo + "/check-runs"
    response = requests.post(create_url, headers=headers, json=body, verify=False)
    if response.status_code != 201:
        print(f"create check request error: {response.status_code}, {response.text}")
        raise RuntimeError("create check request error")
    print(f"create check result: {response.text}")


def update_check(owner: str, repo: str, pull_id: int, name: str, status: str, conclusion: str = None, 
                 output_path: str = None, pull_request_id: str = None):
    if not pull_request_id:
        print(f"update_check get pull info...pull id : {pull_id}, ci name: {name}")
        pull_url = GiteeConfig.URL_ROOT + owner + "/" + repo + "/pulls/" + str(pull_id)
        response = requests.get(pull_url, verify=False, headers=get_headers(pull_url))
        if response.status_code != 200:
            print(f"pull get error: {response.status_code}")
            return
        response_json = json.loads(response.text)
        pull_request_id = response_json["id"]
        print(f"update check pull_request_id: {pull_request_id}")

    pr_url = "https://gitee.com/" + owner + "/" + repo + "/runs/pr_check_runs?pull_request_ids=" + str(pull_request_id)
    print("get check info...")
    response = requests.get(pr_url, verify=False)
    if response.status_code != 200:
        print(f"pr runs get error: {response.status_code}")
        return
    response_json = json.loads(response.text)
    check_runs = response_json["data"][str(pull_request_id)]["check_runs"]
    check_run_id = None
    for check_run in check_runs:
        if check_run["name"] == name:
            check_run_id = check_run["id"]
    if check_run_id is None:
        print("not find check_run")
        return

    details_url = None
    started_at = None
    completed_at = None
    output = None
    actions = None

    if output_path:
        file_json = get_file_data(output_path)
        if file_json is not None:
            details_url = file_json.get("details_url")
            started_at = file_json.get("started_at")
            completed_at = file_json.get("complete_at")
            output = file_json.get("output")
            actions = file_json.get("actions")
            if completed_at is not None or status == "completed":
                if conclusion is None:
                    print("conclusion can't be none when status is completed")
                    return
                if conclusion == "action_required" and details_url is None:
                    print("detail_url must be not none")
                    return
                
        body = {
            "name": name,
            "check_run_id": check_run_id,
            "status": status,
            "conclusion": conclusion,
            "details_url": details_url,
            "started_at": started_at,
            "completed_at": completed_at,
            "output": output,
            "actions": actions
        }

    else:
        body = {
            "name": name,
            "check_run_id": check_run_id,
            "status": status,
            "conclusion": conclusion
        }

    update_url = GiteeConfig.URL_ROOT + owner + "/" + repo + "/check-runs/" + str(check_run_id)
    print(f"update check {name}...")
    response = requests.patch(update_url, headers=headers, json=body, verify=False)
    if response.status_code != 200:
        print(f"update check request error: {response.status_code}")
        return
    print(f"update check result: {response.text}")


def get_file_data(output_path: str):
    if not os.path.exists(output_path):
        print("检查报告文件不存在！")
        return None
    with open(output_path, "r", encoding="utf-8") as file:
        output_path = None
        try:
            output_path = json.loads(file.read())
        except json.JSONDecodeError:
            print("output json parse error")
        return output_path
